package main

import (
	"vpn-server/config"
	"vpn-server/controller"
	"vpn-server/datasource"
	"vpn-server/middleware"
	"vpn-server/service"

	"github.com/kataras/iris/v12"
	"github.com/kataras/iris/v12/mvc"
)

func main() {
	app := newApp()

	//应用App设置
	configation(app)

	//路由设置
	mvcHandle(app)

	config := config.InitConfig()
	addr := ":" + config.Port
	app.Run(
		iris.Addr(addr), //在端口8080进行监听
		iris.WithoutServerError(iris.ErrServerClosed), //无服务错误提示
		iris.WithOptimizations,                        //对json数据序列化更快的配置
	)
}

//构建App
func newApp() *iris.Application {
	app := iris.New()

	//设置日志级别  开发阶段为debug
	app.Logger().SetLevel("debug")

	//app.StaticContent()
	// //注册静态资源
	// app.StaticWeb("/static", "./static")
	// app.StaticWeb("/manage/static", "./static")
	// app.StaticWeb("/img", "./static/img")

	// //注册视图文件
	// app.RegisterView(iris.HTML("./static", ".html"))
	// app.Get("/", func(context context.Context) {
	// 	context.View("index.html")
	// })

	return app
}

/**
 * MVC 架构模式处理
 */
func mvcHandle(app *iris.Application) {

	//启用session
	// sessManager := sessions.New(sessions.Config{
	// 	Cookie:  "sessioncookie",
	// 	Expires: 24 * time.Hour,
	// })

	db := datasource.NewMysqlEngine()

	//登录模块，保护下发token和刷新token的功能
	authService := service.NewAuthService(db)

	auth := mvc.New(app.Party("/auth"))

	auth.Register(
		authService,
	)
	auth.Handle(new(controller.AuthController))

	//需要验证的模块 这以下的都需要注入 NewVerifyMiddleware 中间件

	userService := service.NewUserService(db)
	user := mvc.New(app.Party("/user"))
	user.Router.Use(middleware.NewVerifyMiddleware())
	user.Register(
		userService,
	)
	user.Handle(new(controller.UserController))
}

/**
 * 项目设置
 */
func configation(app *iris.Application) {

	//配置 字符编码
	app.Configure(iris.WithConfiguration(iris.Configuration{
		Charset: "UTF-8",
	}))

	//错误配置
	//未发现错误
	app.OnErrorCode(iris.StatusNotFound, func(context iris.Context) {
		context.JSON(iris.Map{
			"errmsg": iris.StatusNotFound,
			"msg":    " not found ",
			"data":   iris.Map{},
		})
	})

	app.OnErrorCode(iris.StatusInternalServerError, func(context iris.Context) {
		context.JSON(iris.Map{
			"errmsg": iris.StatusInternalServerError,
			"msg":    " interal error ",
			"data":   iris.Map{},
		})
	})
}
